package com.zbkj.crmeb.merchant.admin.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.ProductConvertUtil;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.export.vo.SupplierProductExcelVo;
import com.zbkj.crmeb.export.vo.UploadSupplierProductExcel2Vo;
import com.zbkj.crmeb.export.vo.UploadSupplierProductExcelVo;
import com.zbkj.crmeb.image.model.ProductImage;
import com.zbkj.crmeb.image.service.ProductImageService;
import com.zbkj.crmeb.merchant.admin.service.StoreProductStockService;
import com.zbkj.crmeb.merchant.admin.service.SupplierStoreProductService;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.*;
import com.zbkj.crmeb.store.response.*;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.system.service.SystemAttachmentService;
import com.zbkj.crmeb.system.service.SystemCountryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class SupplierStoreProductServiceImpl extends ServiceImpl<StoreProductDao, StoreProduct> implements SupplierStoreProductService {

    @Resource
    private StoreProductDao storeProductDAO;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private StoreProductStockService storeProductStockService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    private StoreProductDraftService storeProductDraftService;
    @Autowired
    private StoreProductAttrValueDraftService storeProductAttrValueDraftService;
    @Autowired
    private StoreProductUploadService storeProductUploadService;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private StoreProductNormService storeProductNormService;
    @Autowired
    private StoreProductNormDescriptionService storeProductNormDescriptionService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    ProductImageService productImageService;
    @Autowired
    private SystemCountryService systemCountryService;

    @Value("${aliyun.oss.oss-url}")
    private String ossUrl;

    @Override
    public PageInfo<StoreProductResponse> supplierProductList(SupplierStoreProductSearchRequest request, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, supplierInfo.getSupplierId());
        Page<StoreProduct> storeProductPage = PageHelper.startPage(request.getPage(), request.getLimit());
        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(storeProducts)) {
            return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
        }
        // 匹配详情属性
        productConvertUtil.convertProductImage(storeProducts);
        List<Integer> ids = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
        // 处理attrValue数据
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, ids)
        );
        storeProductStockService.showStockBatch(attrValues);
        Map<Integer, List<StoreProductAttrValue>> attrValueMap = attrValues.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
        List<Integer> cateIdList = storeProducts.stream().map(StoreProduct::getCateId).distinct().collect(Collectors.toList());
        Map<String, String> cateMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(cateIdList)){
            List<CategoryMatch> categoryMatchList = categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().in(CategoryMatch::getId, cateIdList));
            cateMap = categoryMatchList.stream().collect(Collectors.toMap(e->e.getId().toString(), CategoryMatch::getName));
        }
        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();
            //todo 价格币种待确定
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            //分类
            storeProductResponse.setCateValues(cateMap.get(storeProductResponse.getCateId()));
            // 查询对应属性赋值
            if (attrValueMap.get(id) == null) {
                continue;
            }
            List<StoreProductAttrValue> values = attrValueMap.get(id);
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            for (StoreProductAttrValue value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
            }
            storeProductResponse.setAttrValue(valueResponses);
            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            //设置销售状态库存小于0售罄，大于0上架为在售，下架为仓库中
            storeProductResponse.setSalesStatus(storeProductResponse.getStock() > 0 ? (storeProductResponse.getIsShow() ? 1 : 0) :  2);
            storeProductResponses.add(storeProductResponse);
        }
        return CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
    }

    @Override
    public StoreProductUpload importProductList(List<UploadSupplierProductExcelVo> list,Integer merId) {
        //获取供应商信息
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        //导入商品总数
        int total = list.size();
        //导入商品所有分类id
        List<Integer> cateIdList = list.stream().map(UploadSupplierProductExcelVo::getCateId).distinct().collect(Collectors.toList());
        cateIdList.removeIf(Objects::isNull);
        //获取系统存在的分类id
        List<Integer> cateList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(cateIdList)){
            cateList = categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().eq(CategoryMatch::getType, 1).in(CategoryMatch::getId,cateIdList)
                    .select(CategoryMatch::getId)).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        }
        //导入商品品牌id
        List<Integer> brandIdList = list.stream().map(UploadSupplierProductExcelVo::getBrandId).distinct().collect(Collectors.toList());
        brandIdList.removeIf(Objects::isNull);
        //品牌id与名称映射关系
        Map<Integer,String> brandMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(brandIdList)){
            brandMap = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery().eq(StoreBrand::getType, 1).in(StoreBrand::getId,brandIdList)
                    .select(StoreBrand::getId,StoreBrand::getEnName)).stream().collect(Collectors.toMap(StoreBrand::getId,StoreBrand::getEnName));
        }
//        List<Integer> cateList = categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().eq(CategoryMatch::getType, 1).select(CategoryMatch::getId)).stream().map(CategoryMatch::getId).collect(Collectors.toList());
//        Map<Integer,String> brandMap = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery().eq(StoreBrand::getType, 1).select(StoreBrand::getId,StoreBrand::getEnName)).stream().collect(Collectors.toMap(StoreBrand::getId,StoreBrand::getEnName));
        //发货地id
        List<Integer> tempIdList = Arrays.stream(StockAreaTempEnum.values()).map(StockAreaTempEnum::getTempId).collect(Collectors.toList());
        Set<UploadSupplierProductExcelVo> draftProductSet = new HashSet<>();
        //失败数量
        int sum = groupProductList(list, cateList, brandMap, tempIdList, draftProductSet);
        //上传商品去除草稿箱中的商品
        list.removeAll(draftProductSet);
        //根据国际编码进行分组，得到map
        Map<String, List<UploadSupplierProductExcelVo>> productMap = list.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getKeyword));
        //正常商品
        for (Entry<String, List<UploadSupplierProductExcelVo>> productListEntry : productMap.entrySet()) {
            List<UploadSupplierProductExcelVo> productList = productListEntry.getValue();
            //同一个国际编码的商品根据发货地分组
            Map<Integer, List<UploadSupplierProductExcelVo>> tempMap = productList.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getTempId));
            for (Entry<Integer, List<UploadSupplierProductExcelVo>> tempEntry : tempMap.entrySet()) {
                List<UploadSupplierProductExcelVo> tempList = tempEntry.getValue();
                //去除色号为空的商品，并通过色号分组
                Map<String, List<UploadSupplierProductExcelVo>> colorMap = tempList.stream().filter(item-> StringUtils.isNotBlank(item.getColorCode())).collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getColorCode));
                //色号为空的商品集合
                List<UploadSupplierProductExcelVo> productExcelVoList = tempList.stream().filter(item -> StringUtils.isBlank(item.getColorCode())).collect(Collectors.toList());
                //存在色号为空的商品，存入map中
                if(CollectionUtils.isNotEmpty(productExcelVoList)){
                    colorMap.put(null,productExcelVoList);
                }
                for (Entry<String, List<UploadSupplierProductExcelVo>> colorEntry : colorMap.entrySet()) {
                    List<UploadSupplierProductExcelVo> colorList = colorEntry.getValue();
                    //尺码与商品信息映射关系
                    Map<String, UploadSupplierProductExcelVo> map = colorList.stream().collect(Collectors.toMap(UploadSupplierProductExcelVo::getSkuSize, e -> e,(value1, value2) -> value2));
                    List<UploadSupplierProductExcelVo> sizeList = new ArrayList<>(map.values());
                    //计算商品总库存
                    int stock = sizeList.stream().mapToInt(UploadSupplierProductExcelVo::getAttrStock).sum();
                    StoreProductCrmebRequest storeProductCrmebRequest = this.buildImportProduct(sizeList, tempEntry.getKey(),colorEntry.getKey(),supplierInfo);
                    //通过barcode获取是否有该商品
                    StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode());
                    if(storeProduct != null && !Objects.equals(storeProduct.getCommodityType(),2)){
                        continue;
                    }
                    //没有该商品，保存该商品，或者商品类型为2
                    storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock, merId);
                }
            }
        }
        //异常商品（加入草稿箱）
        Map<String, List<UploadSupplierProductExcelVo>> draftProductMap = draftProductSet.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getKeyword));
        //异常商品（加入草稿箱）
        for (Entry<String, List<UploadSupplierProductExcelVo>> draftProductEntry : draftProductMap.entrySet()) {
            List<UploadSupplierProductExcelVo> draftProductList = draftProductEntry.getValue();
            Map<Integer, List<UploadSupplierProductExcelVo>> draftTempMap = draftProductList.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getTempId));
            for (Entry<Integer, List<UploadSupplierProductExcelVo>> draftTempEntry : draftTempMap.entrySet()) {
                List<UploadSupplierProductExcelVo> draftTempList = draftTempEntry.getValue();
                Map<String, List<UploadSupplierProductExcelVo>> draftColorMap = draftTempList.stream().filter(item-> StringUtils.isNotBlank(item.getColorCode())).collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getColorCode));
                List<UploadSupplierProductExcelVo> productExcelVoList = draftTempList.stream().filter(item -> StringUtils.isBlank(item.getColorCode())).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(productExcelVoList)){
                    draftColorMap.put(null,productExcelVoList);
                }
                for (Entry<String, List<UploadSupplierProductExcelVo>> draftColorEntry : draftColorMap.entrySet()) {
                    Map<String, UploadSupplierProductExcelVo> map = draftColorEntry.getValue().stream().collect(Collectors.toMap(UploadSupplierProductExcelVo::getSkuSize, e -> e,(value1, value2) -> value2));
                    List<UploadSupplierProductExcelVo> sizeList = new ArrayList<>(map.values());
                    //将草稿箱中的商品保存入数据库
                    UploadSupplierProductExcelVo excelVo = sizeList.get(0);
                    // barcode
                    String barCode = supplierInfo.getBarcode() + excelVo.getKeyword() + "-" + draftTempEntry.getKey()+ "-" + draftColorEntry.getKey();
                    StoreProductDraft exitStoreProductDraft = storeProductDraftService.getOne(Wrappers.<StoreProductDraft>lambdaQuery().eq(StoreProductDraft::getBarCode, barCode));
                    StoreProductDraft storeProductDraft = new StoreProductDraft();;
                    if(exitStoreProductDraft != null){
                        storeProductDraft = exitStoreProductDraft;
                    }
                    BeanUtils.copyProperties(excelVo,storeProductDraft,"sliderImage");
                    BigDecimal cost = sizeList.stream().filter(e -> e.getCost() != null && e.getCost().compareTo(BigDecimal.ZERO) > -1).map(UploadSupplierProductExcelVo::getCost).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                    PriceResult priceResult = priceUtil.eur2Rmb(cost);
                    BigDecimal otPrice = sizeList.stream().filter(e -> e.getOtPrice() != null && e.getOtPrice().compareTo(BigDecimal.ZERO) > -1).map(UploadSupplierProductExcelVo::getOtPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                    List<String> collect = Stream.of(excelVo.getImage(), excelVo.getImageUrl1(), excelVo.getImageUrl2(), excelVo.getImageUrl3(), excelVo.getImageUrl4(),
                            excelVo.getImageUrl5(), excelVo.getImageUrl6(), excelVo.getImageUrl7(),excelVo.getImageUrl8(), excelVo.getImageUrl9()).collect(Collectors.toList());
                    collect.removeIf(StringUtils::isBlank);
                    JSONArray gallery = JSONArray.parseArray(JSON.toJSONString(collect));
                    if(gallery.size()>0){
                        storeProductDraft.setSliderImage(gallery.toJSONString());
                    }
                    storeProductDraft.setBarCode(barCode);
                    storeProductDraft.setCost(priceResult.getPrice());
                    storeProductDraft.setPrice(priceResult.getPrice());
                    storeProductDraft.setSourceCost(priceResult.getPrice());
                    storeProductDraft.setExchangeRate(priceResult.getExchangeRate());
                    storeProductDraft.setOtPrice(otPrice);
                    storeProductDraft.setCateId(cateList.contains(excelVo.getCateId()) ? excelVo.getCateId().toString() : null);
                    storeProductDraft.setBrandId(brandMap.containsKey(excelVo.getBrandId()) ? excelVo.getBrandId() : null);
                    storeProductDraft.setBrandName(brandMap.get(storeProductDraft.getBrandId()));
                    //供应商信息填充
                    storeProductDraft.setIsEurope(supplierInfo.getIsEurope());
                    storeProductDraft.setMerId(supplierInfo.getMerchantId());
                    storeProductDraft.setSuppliersId(supplierInfo.getSupplierId().toString());
                    storeProductDraft.setSuppliersName(supplierInfo.getSupplierName());
                    storeProductDraft.setCountryId(systemCountryService.getIdByName(excelVo.getCountry()));
                    if(storeProductDraft.getId()!=null){
                        storeProductDraftService.updateById(storeProductDraft);
                    }else {
                        storeProductDraftService.save(storeProductDraft);
                    }
                    List<StoreProductAttrValueDraft> valueDraftList = new ArrayList<>();
                    for (UploadSupplierProductExcelVo e : sizeList) {
                        String suk = e.getSkuSize();
                        if(StringUtils.isNotBlank(e.getSkuColor())){
                            suk = e.getSkuColor()+"-"+e.getSkuSize();
                        }
                        StoreProductAttrValueDraft valueDraft = new StoreProductAttrValueDraft();
                        if(exitStoreProductDraft != null){
                            StoreProductAttrValueDraft exitValueDraft = storeProductAttrValueDraftService.getOne(Wrappers.<StoreProductAttrValueDraft>lambdaQuery().eq(StoreProductAttrValueDraft::getProductId, exitStoreProductDraft.getId())
                                    .eq(StoreProductAttrValueDraft::getSuk, suk).select(StoreProductAttrValueDraft::getId));
                            if(exitValueDraft!= null){
                                valueDraft = exitValueDraft;
                            }
                        }
                        valueDraft.setProductId(storeProductDraft.getId());
                        valueDraft.setBarCode(barCode);
                        valueDraft.setStock(e.getAttrStock());
                        valueDraft.setCost(e.getCost()!=null && e.getCost().compareTo(BigDecimal.ZERO)> -1 ? priceUtil.eur2Rmb(e.getCost()).getPrice():null);
                        valueDraft.setPrice(valueDraft.getCost());
                        valueDraft.setSourceCost(valueDraft.getCost());
                        valueDraft.setOtPrice(e.getOtPrice()!=null && e.getOtPrice().compareTo(BigDecimal.ZERO)> -1 ? e.getOtPrice():null);
                        valueDraft.setImage(StringUtils.isNotBlank(e.getSkuImage()) ? e.getSkuImage() : e.getImage());
                        valueDraft.setSuk(suk);
                        valueDraft.setTempId(excelVo.getTempId());
                        LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                        linkedMap.put("尺寸", valueDraft.getSuk());
                        valueDraft.setAttrValue(JSON.toJSONString(linkedMap));
                        valueDraftList.add(valueDraft);
                    }
                    List<StoreProductAttrValueDraft> updateDraftList = valueDraftList.stream().filter(e -> e.getId() != null).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(updateDraftList)){
                        storeProductAttrValueDraftService.updateBatchById(updateDraftList);
                    }
                    valueDraftList.removeAll(updateDraftList);
                    if(CollectionUtils.isNotEmpty(valueDraftList)){
                        storeProductAttrValueDraftService.saveBatch(valueDraftList);
                    }
                }
            }
        }
        String msg = "总计:"+total+",成功:"+list.size()+",草稿箱:"+draftProductSet.size()+",失败:"+sum;
        //添加日志
        StoreProductUpload storeProductUpload = new StoreProductUpload();
        storeProductUpload.setMsg(msg);
        storeProductUpload.setSupplierId(supplierInfo.getSupplierId());
        storeProductUploadService.save(storeProductUpload);
        return storeProductUpload;
    }

    @Override
    public PageInfo<StoreProductResponse> supplierDraftProductList(SupplierStoreProductSearchRequest request, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        LambdaQueryWrapper<StoreProductDraft> lambdaQueryWrapper = getDraftProductQueryWrapper(request, supplierInfo.getSupplierId());
        Page<StoreProductDraft> storeProductPage = PageHelper.startPage(request.getPage(), request.getLimit());
        List<StoreProductDraft> storeProducts = storeProductDraftService.list(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(storeProducts)) {
            return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
        }
        // 匹配详情属性
        productConvertUtil.convertProductDraftImage(storeProducts);
        List<Integer> ids = storeProducts.stream().map(StoreProductDraft::getId).collect(Collectors.toList());
        // 处理attrValue数据
        List<StoreProductAttrValueDraft> attrValues = storeProductAttrValueDraftService.list(Wrappers.<StoreProductAttrValueDraft>lambdaQuery()
                .in(StoreProductAttrValueDraft::getProductId, ids)
        );
        Map<Integer, List<StoreProductAttrValueDraft>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValueDraft::getProductId,
                s -> {
                    List<StoreProductAttrValueDraft> list = new ArrayList<>();
                    list.add(s);
                    return list;
                },
                (List<StoreProductAttrValueDraft> value1, List<StoreProductAttrValueDraft> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for (StoreProductDraft product : storeProducts) {
            Integer id = product.getId();
            //todo 价格币种待确定
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            // 查询对应属性赋值
            if (attrValueMap.get(id) == null) {
                continue;
            }
            List<StoreProductAttrValueDraft> values = attrValueMap.get(id);
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            for (StoreProductAttrValueDraft value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
            }
            storeProductResponse.setAttrValue(valueResponses);
            storeProductResponses.add(storeProductResponse);
        }
        return CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
    }

    @Override
    public StoreProductNormResponse supplierProductInfo(Integer id, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        //查询该商品
        StoreProduct product = storeProductDAO.selectOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getId, id).eq(StoreProduct::getSuppliersId, supplierInfo.getSupplierId()).eq(StoreProduct::getIsDel, 0));
        if(product == null){
            throw new CrmebException("该商品不存在");
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(product);
        StoreProductNormResponse response = new StoreProductNormResponse();
        StoreProductResponse storeProductResponse = getStoreProductResponse(product);
        List<StoreProductResponse> responseList = Collections.singletonList(storeProductResponse);
        response.setProducts(responseList);
        Integer normId = product.getNormId();
        if(null != normId) {
            response.setProductNorm(storeProductNormService.getById(normId));
            String description = storeProductNormDescriptionService.getProductNormDesc(normId);
            if (Objects.nonNull(response.getProductNorm()) && StringUtils.isNotBlank(description)) {
                response.getProductNorm().setStoreInfo(description);
            }
        } else {
            StoreProductNorm norm = new StoreProductNorm();
            BeanUtils.copyProperties(responseList.get(0), norm);
            response.setProductNorm(norm);
        }
        return response;
    }

    @Override
    public StoreProductResponse supplierDraftProductInfo(Integer id, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        StoreProductDraft storeProductDraft = storeProductDraftService.getOne(Wrappers.<StoreProductDraft>lambdaQuery().eq(StoreProductDraft::getId, id).eq(StoreProductDraft::getSuppliersId, supplierInfo.getSupplierId()).eq(StoreProductDraft::getIsDel, 0));
        if(storeProductDraft == null){
            throw new CrmebException("该商品不存在");
        }
        // 处理attrValue数据
        List<StoreProductAttrValueDraft> attrValues = storeProductAttrValueDraftService.list(Wrappers.<StoreProductAttrValueDraft>lambdaQuery()
                .eq(StoreProductAttrValueDraft::getProductId, id));
        StoreProductResponse storeProductResponse = new StoreProductResponse();
        BeanUtils.copyProperties(storeProductDraft, storeProductResponse);
        storeProductResponse.setCateId(Integer.valueOf(storeProductDraft.getCateId()));
        List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
        for (StoreProductAttrValueDraft value : attrValues) {
            StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
            BeanUtils.copyProperties(value, valueResponse);
            valueResponses.add(valueResponse);
        }
        storeProductResponse.setAttrValue(valueResponses);
        return storeProductResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSupplierProduct(SupplierProductRequest request, Integer merId) {

        //设置重量
        CategoryMatch categoryMatch = categoryMatchService.getById(request.getCateId());
        if (Objects.isNull(request.getWeight())){
            request.setWeight(categoryMatch.getWeight());
        }
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        StoreProduct product = storeProductDAO.selectOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getId, request.getId()).eq(StoreProduct::getSuppliersId, supplierInfo.getSupplierId()).eq(StoreProduct::getIsDel, 0));
        if(product == null){
            throw new CrmebException("该商品不存在");
        }
        if(Objects.equals(product.getIsEurope(), ProductTypeEnum.INSIDE.getCode())){
            throw new CrmebException("自建转云仓商品需要在商户后台编辑");
        }
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(request, storeProduct);
        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));
        StoreBrand storeBrand = storeBrandService.getById(storeProduct.getBrandId());
        if(null!=storeBrand){
            storeProduct.setBrandName(storeBrand.getEnName());
        }
        calcPriceForAttrValues(request, storeProduct);
        int saveCount = storeProductDAO.updateById(storeProduct);
        // 对attr表做全量更新，删除原有数据保存现有数据
        storeProductAttrService.removeByProductId(storeProduct.getId());
        // 查出所有的sku属性,用suk找到相同的属性,做更新
//        List<StoreProductAttrValue> attrValueist = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeProduct.getId()));
//        Map<String, StoreProductAttrValue> attrValueMap = attrValuelist == null ? MapUtil.newHashMap() : attrValuelist.stream().collect(Collectors.toMap(StoreProductAttrValue::getSuk, Function.identity()));
        if (CollectionUtils.isNotEmpty(request.getAttrValue())) {
            request.getAttrValue().forEach(attrValueRequest -> {
                if (null != attrValueRequest.getAttrValue()) {
                    List<String> skuList = new ArrayList<>();
                    for (Map.Entry<String, String> vo : attrValueRequest.getAttrValue().entrySet()) {
                        skuList.add(vo.getValue());
                    }
                    attrValueRequest.setSuk(String.join(",", skuList));
//                    attrValueRequest.setId(attrValueMap.containsKey(attrValueRequest.getSuk()) ? attrValueMap.get(attrValueRequest.getSuk()).getId() : null);
                }
            });
        }
        if (request.getSpecType()) {
            request.getAttr().forEach(e -> {
                e.setProductId(request.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            storeProductAttrService.saveBatch(request.getAttr());
            if (CollectionUtils.isNotEmpty(request.getAttrValue())) {

                List<StoreProductAttrValue> oldAttrValueList = storeProductAttrValueService.listByProductId(request.getId());
                Map<String, StoreProductAttrValue> oldAttrValueMap = oldAttrValueList.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, e -> e, (e1, e2) -> e2));

                storeProductAttrValueService.removeByProductId(request.getId());
                List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = request.getAttrValue();
                // 批量设置attrValues对象的商品id
                storeProductAttrValuesRequest.forEach(e -> e.setProductId(request.getId()));
                List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();

                for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                    if (StringUtils.isBlank(attrValuesRequest.getBarCode())){
                        attrValuesRequest.setBarCode(product.getBarCode());
                    }

                    StoreProductAttrValue spav = new StoreProductAttrValue();
                    attrValuesRequest.setSourceCost(attrValuesRequest.getPrice());
                    attrValuesRequest.setCost(attrValuesRequest.getPrice());
                    attrValuesRequest.setSourceSkuId(attrValuesRequest.getBarCode()+"-"+attrValuesRequest.getSuk());
                    BeanUtils.copyProperties(attrValuesRequest, spav);

                    String sourceSkuId = spav.getSourceSkuId();

                    StoreProductAttrValue oldAttrValue = oldAttrValueMap.get(sourceSkuId);
                    log.info("editStock 商品的库存量1：{}, {}",JSON.toJSONString(spav),JSON.toJSONString(oldAttrValue) );
                    storeProductStockService.editStock(spav, oldAttrValue);


                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    storeProductAttrValues.add(spav);
                }

                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                // attrResult整存整取，不做更新
                storeProductAttrResultService.deleteByProductId(storeProduct.getId());
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0, */storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(request.getAttrValue())), DateUtil.getNowTime(), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                if (!saveOrUpdateResult){
                    throw new CrmebException("编辑属性详情失败");
                }
            }
        } else {
            List<StoreProductAttrValue> oldAttrValuelist = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeProduct.getId()));

            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            if (!attrAddResult){
                throw new CrmebException("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            if (request.getAttrValue().size() == 0){
                throw new CrmebException("attrValue不能为空");
            }
            StoreProductAttrValueRequest attrValueRequest = request.getAttrValue().get(0);
            attrValueRequest.setSourceCost(attrValueRequest.getPrice());
            attrValueRequest.setCost(attrValueRequest.getPrice());
            attrValueRequest.setSuk("默认");
            attrValueRequest.setProductId(storeProduct.getId());
            BeanUtils.copyProperties(attrValueRequest, singleAttrValue);
            singleAttrValue.setImage(systemAttachmentService.clearPrefix(singleAttrValue.getImage()));
            storeProductAttrValueService.removeByProductId(request.getId());
            String sourceSkuId = singleAttrValue.getSourceSkuId();

            if(null != sourceSkuId) {
                Map<String, StoreProductAttrValue> oldAttrValueMap = oldAttrValuelist == null ? MapUtil.newHashMap() : oldAttrValuelist.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, Function.identity(), (v1, v2)->v2));

                StoreProductAttrValue oldAttrValue = oldAttrValueMap.get(sourceSkuId);
                log.info("editStock 商品的库存量2：{}, {}",JSON.toJSONString(singleAttrValue),JSON.toJSONString(oldAttrValue) );
                storeProductStockService.editStock(singleAttrValue, oldAttrValue);

            }

            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            if (!saveOrUpdateResult){
                throw new CrmebException("新增属性详情失败");
            }
        }

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, storeProduct.getId())
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

        return saveCount > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUpdateSupplierProduct(SupplierProductRequest request, Integer supplierId) {
        if (CollectionUtils.isEmpty(request.getIds())){
            throw new CrmebException("商品ID为空无法更新");
        }
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(supplierId);
        List<Integer> updateFailList = new ArrayList<>();
        List<Integer> ids = request.getIds();
        for (Integer id : ids) {
            StoreProduct product = storeProductDAO.selectOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getId, id).eq(StoreProduct::getSuppliersId, supplierInfo.getSupplierId()).eq(StoreProduct::getIsDel, 0));
            if(product == null){
                updateFailList.add(id);
                continue;
            }
            if (null != request.getTempId() && request.getTempId() >= 0){
                product.setTempId(request.getTempId());
            }
            int saveCount = storeProductDAO.updateById(product);
            if (saveCount < 1){
                updateFailList.add(id);
            }
        }
        if (CollectionUtils.isNotEmpty(updateFailList)){
            throw new CrmebException("部分商品更新失败: "+JSON.toJSONString(updateFailList));
        }
        return true;
    }

    private void calcPriceForAttrValues(SupplierProductRequest request, StoreProduct storeProduct) {
        if(CollectionUtils.isEmpty(request.getAttrValue())){
            throw new CrmebException("请输入商品sku规格属性");
        }
        List<StoreProductAttrValueRequest> attrValues = request.getAttrValue();
        if (attrValues.stream().anyMatch(e -> e.getPrice() == null || e.getPrice().compareTo(BigDecimal.ZERO) < 0)) {
            throw new CrmebException("售价不能为空或小于0");
        }
        if (attrValues.stream().anyMatch(e -> e.getOtPrice() == null || e.getOtPrice().compareTo(BigDecimal.ZERO) < 0)) {
            throw new CrmebException("原价不能为空或小于0");
        }
        if (attrValues.stream().anyMatch(e -> e.getStock() == null || e.getStock() < 0)) {
            throw new CrmebException("库存不能为空或小于0");
        }
        //总库存
        int stock = request.getAttrValue().stream().mapToInt(StoreProductAttrValueRequest::getStock).sum();
        double sellPrice, otPrice;
        if(stock > 0){
            sellPrice = request.getAttrValue().stream().filter(e->e.getStock() > 0).mapToDouble(e -> e.getPrice().doubleValue()).min().orElse(0);
            // 原价
            otPrice = request.getAttrValue().stream().filter(e->e.getStock() > 0).mapToDouble(e -> e.getOtPrice().doubleValue()).min().orElse(0);
        }else {
            sellPrice = request.getAttrValue().stream().mapToDouble(e -> e.getPrice().doubleValue()).min().orElse(0);
            otPrice = request.getAttrValue().stream().mapToDouble(e -> e.getOtPrice().doubleValue()).min().orElse(0);
        }
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);
        storeProduct.setCost(storeProduct.getPrice());
        storeProduct.setSourceCost(storeProduct.getPrice());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSupplierDraftProduct(SupplierProductRequest supplierProductRequest, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        StoreProductDraft storeProductDraft = storeProductDraftService.getOne(Wrappers.<StoreProductDraft>lambdaQuery().eq(StoreProductDraft::getId, supplierProductRequest.getId()).eq(StoreProductDraft::getSuppliersId, supplierInfo.getSupplierId()).eq(StoreProductDraft::getIsDel, 0));
        if(storeProductDraft == null){
            throw new CrmebException("该商品不存在");
        }
        StoreProduct product = storeProductService.getByBarCode(storeProductDraft.getBarCode());
        if(product != null && !product.getId().equals(supplierProductRequest.getId())){
            throw new CrmebException("该商品唯一编码已存在");
        }
        supplierProductRequest.setBarCode(storeProductDraft.getBarCode());
        boolean save = saveProduct(supplierProductRequest,supplierInfo);
        //删除草稿箱
        storeProductDraftService.removeById(supplierProductRequest.getId());
        storeProductAttrValueDraftService.remove(Wrappers.<StoreProductAttrValueDraft>lambdaQuery().eq(StoreProductAttrValueDraft::getProductId,supplierProductRequest.getId()));
        return save;
    }

    @Override
    public boolean addSupplierProduct(SupplierProductRequest storeProductRequest, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        String barcode = supplierInfo.getBarcode()+storeProductRequest.getKeyword()+"-"+storeProductRequest.getTempId();
        if(StringUtils.isNotBlank(storeProductRequest.getColorCode())){
            barcode = barcode + "-" + storeProductRequest.getColorCode();
        }
        StoreProduct product = storeProductService.getByBarCode(barcode);
        if(product != null){
            throw new CrmebException("该商品唯一编码已存在");
        }
        //设置barCode
        storeProductRequest.setBarCode(barcode);
        //设置重量
        CategoryMatch categoryMatch = categoryMatchService.getById(storeProductRequest.getCateId());
        if (Objects.isNull(storeProductRequest.getWeight())){
            storeProductRequest.setWeight(categoryMatch.getWeight());
        }
        return saveProduct(storeProductRequest,supplierInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSupplierDraftProduct(List<Integer> ids, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        if(CollectionUtils.isEmpty(ids)){
            return false;
        }
        List<StoreProductDraft> list = storeProductDraftService.list(Wrappers.<StoreProductDraft>lambdaQuery().eq(StoreProductDraft::getSuppliersId, supplierInfo.getSupplierId()).in(StoreProductDraft::getId, ids).select(StoreProductDraft::getId));
        List<Integer> collect = list.stream().map(StoreProductDraft::getId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(collect)){
            return false;
        }
        boolean remove = storeProductDraftService.removeByIds(collect);
        if(remove){
            storeProductAttrValueDraftService.remove(Wrappers.<StoreProductAttrValueDraft>lambdaQuery().in(StoreProductAttrValueDraft::getProductId,collect));
        }
        return remove;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchShow(BatchEnabledRequest request, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        List<StoreProduct> storeProductList = this.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, request.getProductIdList()));
        List<StoreProduct> productList = storeProductList.stream().filter(e -> Objects.equals(e.getSuppliersId().toString(), supplierInfo.getSupplierId()+"")).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(productList)){
            throw new CrmebException("所选商品不存在");
        }
        if(productList.stream().anyMatch(e->Objects.equals(e.getIsEurope(),ProductTypeEnum.INSIDE.getCode()))){
            throw new CrmebException("所选商品存在自建商品，请重新选择");
        }
        boolean update;
        if(Objects.equals(request.getIsNotShow(),"0")){
            productList = storeProductList.stream().filter(e -> e.getStock() > 0).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(productList)){
                throw new CrmebException("所选商品库存全部为0!");
            }
            update = this.update(Wrappers.<StoreProduct>lambdaUpdate().set(StoreProduct::getIsShow, true).in(StoreProduct::getId, productList.stream().map(StoreProduct::getId).collect(Collectors.toList())));
        }else if(Objects.equals(request.getIsNotShow(),"1")){
            update = this.update(Wrappers.<StoreProduct>lambdaUpdate().set(StoreProduct::getIsShow,false).in(StoreProduct::getId,productList.stream().map(StoreProduct::getId).collect(Collectors.toList())));
        }else {
            throw new CrmebException("状态异常");
        }
        return update;
    }

    @Override
    public PageInfo<StoreProductUpload> uploadList(PageParamRequest request, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        Page<StoreProductUpload> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<StoreProductUpload> list = storeProductUploadService.list(Wrappers.<StoreProductUpload>lambdaQuery().eq(StoreProductUpload::getSupplierId, supplierInfo.getSupplierId()).orderByDesc(StoreProductUpload::getId));
        return CommonPage.copyPageInfo(page, list);
    }

    @Override
    public List<SupplierProductExcelVo> parseExportList(List<StoreProductResponse> productList) {
        List<SupplierProductExcelVo> list = new ArrayList<>();
        List<CategoryMatch> categoryMatchList = categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().eq(CategoryMatch::getType, 1));
        Map<Integer, CategoryMatch> categoryMatchMap = categoryMatchList.stream().collect(Collectors.toMap(CategoryMatch::getId, s -> s));
        for (StoreProductResponse product : productList) {
            for (StoreProductAttrValueResponse value : product.getAttrValue()) {
                SupplierProductExcelVo vo = new SupplierProductExcelVo();
                BeanUtils.copyProperties(product,vo);
                String imgUrl = product.getImage();
                imgUrl = StringUtil.isEmpty(imgUrl) ? "" : imgUrl.substring(0, !imgUrl.contains("?") ? imgUrl.length() : imgUrl.indexOf("?"))+"?x-oss-process=image/resize,m_fill,w_100,h_100";
                vo.setImage(imgUrl);
                CategoryMatch categoryMatch = categoryMatchMap.get(product.getCateId());
                vo.setCateName(Objects.isNull(categoryMatch) ? "" : categoryMatch.getName() );
                vo.setTempName(StockAreaTempEnum.getByTempId(product.getTempId()).getStockAreaName());
                vo.setCreateTime(DateFormatUtils.format(product.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                vo.setPriceRmb(value.getPrice());
                vo.setPriceEur(priceUtil.rmb2EurStatic(value.getPrice(),product.getExchangeRate()));
                vo.setOtPriceRmb(priceUtil.eur2RmbStatic(value.getOtPrice(),product.getExchangeRate()));
                vo.setOtPrice(value.getOtPrice());
                vo.setAttrSuk(value.getSuk());
                vo.setAttrStock(value.getStock());
                vo.setLastPushTime(DateFormatUtils.format(product.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public List<StoreProductTabsHeader> getTabsHeader(int merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        List<StoreProductTabsHeader> headers = new ArrayList<>();
        StoreProductTabsHeader header1 = new StoreProductTabsHeader(0, "出售中商品", 1);
        StoreProductTabsHeader header2 = new StoreProductTabsHeader(0, "仓库中商品", 2);
        StoreProductTabsHeader header3 = new StoreProductTabsHeader(0, "已经售馨商品", 3);
//        StoreProductTabsHeader header4 = new StoreProductTabsHeader(0, "警戒库存", 4);
//        StoreProductTabsHeader header5 = new StoreProductTabsHeader(0, "商品回收站", 5);
        headers.add(header1);
        headers.add(header2);
        headers.add(header3);
        headers.forEach(storeProductTabsHeader -> {
            SupplierStoreProductSearchRequest request = new SupplierStoreProductSearchRequest();
            request.setType(storeProductTabsHeader.getType());
            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, supplierInfo.getSupplierId());
            storeProductTabsHeader.setCount(storeProductDAO.selectCount(lambdaQueryWrapper));
        });
        return headers;
    }

    /**
     * 功能描述: 批量下架商品
     * @Param: [ids]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2023/4/6 16:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUndercarriage(List<Integer> ids, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        return storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                .eq(StoreProduct::getSuppliersId, supplierInfo.getSupplierId())
                .in(StoreProduct::getId, ids)
                .set(StoreProduct::getIsShow, 0));
    }

    private boolean saveProduct(SupplierProductRequest storeProductRequest, SupplierInfo supplierInfo) {
        StoreBrand storeBrand = storeBrandService.getById(storeProductRequest.getBrandId());
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductRequest, storeProduct);
        //storeProduct.setIsShow(true);
        storeProduct.setCreateTime(new Date());
        if(null!=storeBrand){
            storeProduct.setBrandName(storeBrand.getEnName());
        }
        //供应商信息
        storeProduct.setMerId(supplierInfo.getMerchantId());
        storeProduct.setIsEurope(supplierInfo.getIsEurope());
        storeProduct.setSuppliersId(supplierInfo.getSupplierId());
        storeProduct.setSuppliersName(supplierInfo.getSupplierName());
        // storeProduct.setConvertIsEurope(supplierInfo.getIsEurope());
        if(StrUtil.isEmpty(storeProduct.getSyncKeyword())){
            storeProduct.setSyncKeyword(storeProduct.getKeyword());
        }
        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));
        storeProduct.setCommodityType(2);
        //计算价格
        calcPriceForAttrValues(storeProductRequest, storeProduct);
        //保存数据
        boolean save = save(storeProduct);
        if (storeProductRequest.getSpecType()) {
            storeProductRequest.getAttr().forEach(e -> {
                e.setProductId(storeProduct.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
                e.setBarCode(storeProduct.getBarCode());
            });
            boolean attrAddResult = storeProductAttrService.saveBatch(storeProductRequest.getAttr());
            if (!attrAddResult) {
                log.info("--------------- 新增多属性名失败, 商品id: {} ---------------", storeProduct.getId());
                throw new CrmebException("新增属性名失败");
            }
        } else { // 单属性
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            singleAttr.setBarCode(storeProduct.getBarCode());
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            if (!attrAddResult) {
                log.info("--------------- 新增属性名失败, 商品id: {} ---------------", storeProduct.getId());
                throw new CrmebException("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            BigDecimal commissionL1 = BigDecimal.ZERO;
            BigDecimal commissionL2 = BigDecimal.ZERO;
            if (storeProductRequest.getAttrValue().size() > 0) {
                commissionL1 = null != storeProductRequest.getAttrValue().get(0).getBrokerage() ? storeProductRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
                commissionL2 = null != storeProductRequest.getAttrValue().get(0).getBrokerageTwo() ? storeProductRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
            }

            singleAttrValue.setProductId(storeProduct.getId())
                    .setStock(storeProduct.getStock())
                    .setSuk("默认")
                    .setAttrValue("{\"尺寸\":\"默认\"}")
                    .setSales(storeProduct.getSales())
                    .setPrice(storeProduct.getPrice())
                    .setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()))
                    .setCost(storeProduct.getCost())
                    .setSourceCost(storeProduct.getCost())
                    .setBarCode(storeProduct.getBarCode()).setSourceSkuId(storeProduct.getBarCode()+"-默认")
                    .setOtPrice(storeProduct.getOtPrice())
                    .setBrokerage(commissionL1).setBrokerageTwo(commissionL2);
            singleAttrValue.setBarCode(storeProduct.getBarCode());
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            
            if (!saveOrUpdateResult){
                log.info("--------------- 新增属性详情失败, 商品id: {} ---------------", storeProduct.getId());
                throw new CrmebException("新增属性详情失败");
            }
        }
        if (null != storeProductRequest.getAttrValue() && storeProductRequest.getAttrValue().size() > 0) {
            // 批量设置attrValues对象的商品id
            List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductRequest.getAttrValue();
            storeProductAttrValuesRequest.forEach(e -> {
                e.setProductId(storeProduct.getId());
            });
            List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
            for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                StoreProductAttrValue spav = new StoreProductAttrValue();
                attrValuesRequest.setBarCode(storeProduct.getBarCode());
                attrValuesRequest.setSourceCost(attrValuesRequest.getPrice());
                attrValuesRequest.setCost(attrValuesRequest.getPrice());
                BeanUtils.copyProperties(attrValuesRequest, spav);
                //设置sku字段
                if (null == attrValuesRequest.getAttrValue()) {
                    break;
                }
                List<String> skuList = new ArrayList<>();
                for (Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                    skuList.add(vo.getValue());
                    spav.setSuk(String.join(",", skuList));
                    spav.setSourceSkuId(storeProduct.getBarCode()+"-"+spav.getSuk());
                    attrValuesRequest.setSuk(spav.getSuk());
                    attrValuesRequest.setSourceSkuId(spav.getSourceSkuId());
                }
                spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                storeProductAttrValues.add(spav);
            }
            // 保存属性
            if(storeProductRequest.getSpecType() && storeProductAttrValues.size() <= 0) {
                throw new CrmebException("新增属性详情失败");
            }
            if (storeProductAttrValues.size() > 0) {
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0,*/ storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductRequest.getAttrValue())), DateUtil.getNowTime(), Constants.PRODUCT_TYPE_NORMAL, storeProductRequest.getBarCode());
                attrResult.setBarCode(storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                if (!saveOrUpdateResult) {
                    throw new CrmebException("新增属性详情失败");
                }
            }
        }
        // 处理storeInfo
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescriptionService.save(storeProductDescription);
        return save;
    }

    private StoreProductResponse getStoreProductResponse(StoreProduct product) {
        StoreProductResponse storeProductResponse = new StoreProductResponse();
        BeanUtils.copyProperties(product, storeProductResponse);
        // 商品详情
//        StoreProductDescription sd = storeProductDescriptionService.getOne(new LambdaQueryWrapper<StoreProductDescription>()
//                .eq(StoreProductDescription::getProductId, product.getId())
//                .last("LIMIT 1")
//        );
//        if (null != sd) {
//            storeProductResponse.setStoreInfo(StringUtils.isNotBlank(sd.getDescription())  ? sd.getDescription() : storeProductResponse.getStoreInfo());
//        }
        storeProductResponse.setStockArea(StockAreaTempEnum.getByTempId(product.getTempId()).getStockAreaCode());
        // 设置sku属性
        storeProductResponse.setAttr(storeProductAttrService.getByProductId(product.getId()));
        List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.getListByProductId(product.getId());
        storeProductStockService.showStockBatch(storeProductAttrValues);
        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            return storeProductResponse;
        }
        // H5 端用于生成skuList
        List<StoreProductAttrValueResponse> sPAVResponses = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
            BeanUtils.copyProperties(storeProductAttrValue, atr);
            sPAVResponses.add(atr);
        }
        storeProductResponse.setAttrValue(sPAVResponses);
        return storeProductResponse;
    }

    private LambdaQueryWrapper<StoreProductDraft> getDraftProductQueryWrapper(SupplierStoreProductSearchRequest request, Integer supplierId) {
        LambdaQueryWrapper<StoreProductDraft> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreProductDraft::getIsDel,0).eq(StoreProductDraft::getSuppliersId,supplierId);
        if(CollectionUtils.isNotEmpty(request.getBrandIds())){
            lambdaQueryWrapper.in(StoreProductDraft::getBrandId,request.getBrandIds());
        }
        if (CollectionUtils.isNotEmpty(request.getCateIds())) {
            List<Integer> cateIds = new ArrayList<>();
            request.getCateIds().forEach(cateId -> cateIds.addAll(categoryMatchService.getThreeChildVoListByPid(cateId).stream().map(CategoryMatch::getId).collect(Collectors.toList())));
            if(CollectionUtils.isNotEmpty(cateIds)){
                lambdaQueryWrapper.in(StoreProductDraft::getCateId,cateIds);
            }
        }
        if(request.getIsShow() != null){
            lambdaQueryWrapper.eq(StoreProductDraft::getIsShow,request.getIsShow());
        }
        if (StringUtils.isNotBlank(request.getKeyword())) {
            lambdaQueryWrapper.and(i -> i.or().eq(NumberUtil.isInteger(request.getKeyword()),StoreProductDraft::getId, request.getKeyword())
                    .or().like(StoreProductDraft::getStoreName, request.getKeyword())
                    .or().like(StoreProductDraft::getKeyword, request.getKeyword())
                    .or().like(StoreProductDraft::getBarCode, request.getKeyword()));
        }
        if (StringUtils.isNotBlank(request.getSeasonCode())) {
            if ("-1".equals(request.getSeasonCode())) {
                lambdaQueryWrapper.isNull(StoreProductDraft::getSeasonCode);
            } else {
                lambdaQueryWrapper.likeRight(StoreProductDraft::getSeasonCode, request.getSeasonCode());
            }
        }
        lambdaQueryWrapper.orderByDesc(StoreProductDraft::getLastPushTime);
        return lambdaQueryWrapper;
    }

    private int groupProductList(List<UploadSupplierProductExcelVo> list, List<Integer> cateList, Map<Integer, String> brandMap, List<Integer> tempIdList, Set<UploadSupplierProductExcelVo> draftProductSet) {
        int sum = 0;
        Iterator<UploadSupplierProductExcelVo> it = list.iterator();
        //循环上传商品列表
        while(it.hasNext()){
            UploadSupplierProductExcelVo excelVo = it.next();
            //商品国际编码为空，剔除，失败数+1
            if (StringUtils.isBlank(excelVo.getKeyword())) {
                sum++;
                it.remove();
                continue;
            }
            //发货地为空，或者发货地id填写与系统存在的发货地不符，剔除，失败数+1
            if (excelVo.getTempId() == null || !tempIdList.contains(excelVo.getTempId())) {
                sum++;
                it.remove();
                continue;
            }
            //sku尺码未填写，剔除，失败数+1
            if (StringUtils.isBlank(excelVo.getSkuSize())) {
                sum++;
                it.remove();
                continue;
            }
            //商品主图没有填写，存入草稿箱
            if (StringUtils.isBlank(excelVo.getImage())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //商品名称没有填写，存入草稿箱
            if (StringUtils.isBlank(excelVo.getStoreName())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //商品品牌id未填写，或与存在的商品品牌不符，存入草稿箱
            if (null == excelVo.getBrandId() || !brandMap.containsKey(excelVo.getBrandId())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //分类未填写，或与存在的分类不符，存入草稿箱
            if (excelVo.getCateId() == null || !cateList.contains(excelVo.getCateId())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //售价（欧元）未填写，或售价（欧元）小于0，存入草稿箱
            if (excelVo.getCost() == null || excelVo.getCost().compareTo(BigDecimal.ZERO) < 0) {
                draftProductSet.add(excelVo);
                continue;
            }
            //原价（欧元）未填写，或者原价（欧元）小于0，存入草稿箱
            if (excelVo.getOtPrice() == null || excelVo.getOtPrice().compareTo(BigDecimal.ZERO) < 0) {
                draftProductSet.add(excelVo);
                continue;
            }
            //库存未填写，或库存小于0，存入草稿箱
            if (excelVo.getAttrStock() == null || excelVo.getAttrStock() < 0) {
                draftProductSet.add(excelVo);
            }
        }
        return sum;
    }

    /**
     * 商品构建
     * @author daigb
     * @date:  2022-11-09 16:11
     */
    private StoreProductCrmebRequest buildImportProduct(List<UploadSupplierProductExcelVo> list, Integer tempId, String color, SupplierInfo supplierInfo) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        try {
            UploadSupplierProductExcelVo excelVo = list.get(0);
            List<String> collect = Stream.of(excelVo.getImage(), excelVo.getImageUrl1(), excelVo.getImageUrl2(), excelVo.getImageUrl3(), excelVo.getImageUrl4(),
                    excelVo.getImageUrl5(), excelVo.getImageUrl6(), excelVo.getImageUrl7(),excelVo.getImageUrl8(), excelVo.getImageUrl9()).collect(Collectors.toList());
            collect.removeIf(StringUtils::isBlank);
            JSONArray gallery = JSONArray.parseArray(JSON.toJSONString(collect));
            String mainImage = excelVo.getImage();
            //成本价
            PriceResult priceResult = priceUtil.eur2Rmb(list.stream().map(UploadSupplierProductExcelVo::getCost).min(BigDecimal::compareTo).get());
            BigDecimal cost = priceResult.getPrice();
            //原价
            BigDecimal otPrice = list.stream().map(UploadSupplierProductExcelVo::getOtPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            StoreBrand storeBrand = storeBrandService.getById(excelVo.getBrandId());
            if(null == storeBrand){
                storeBrand = storeBrandService.getById(5429);
            }
            // barcode
            String barCode = supplierInfo.getBarcode() + excelVo.getKeyword() + "-" + tempId+ "-" + color;
            // 判断供应商自动匹配图片
            boolean isImgMatch = false;
            if(ProductTypeEnum.HOLAWINE.getCode().equals(supplierInfo.getIsEurope())
            		|| ProductTypeEnum.XINGFA.getCode().equals(supplierInfo.getIsEurope())
            		|| ProductTypeEnum.LICHENG.getCode().equals(supplierInfo.getIsEurope())
            		|| ProductTypeEnum.MOBAO.getCode().equals(supplierInfo.getIsEurope())
                    || ProductTypeEnum.CRIS.getCode().equals(supplierInfo.getIsEurope())
            		) {
            	isImgMatch = true;
            }
            Map<String, String> skuImg = new HashMap<>();
            if(isImgMatch) {
    			List<ProductImage> productImages = productImageService.list(Wrappers.<ProductImage>lambdaQuery()
    		                    .eq(ProductImage :: getFolderName, excelVo.getKeyword())
    		                    .orderByAsc(ProductImage :: getTypeSort, ProductImage :: getColor, ProductImage :: getSort)
    		                    );
    			if(CollectionUtils.isNotEmpty(productImages)) {
    				// 主图替换
    				mainImage = ossUrl + Constants.UPLOAD_FILE_WAREHOUSE_DIR + productImages.get(0).getUrl();
    				gallery = new JSONArray();
    				// 轮播图替换
    				for(ProductImage img : productImages) {
    					skuImg.put(img.getColor(), ossUrl + Constants.UPLOAD_FILE_WAREHOUSE_DIR + img.getUrl());
    					gallery.add(ossUrl + Constants.UPLOAD_FILE_WAREHOUSE_DIR + img.getUrl());
    				}
    			}
            }
            
            List<StoreProductAttr> attrList = new ArrayList<>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();
            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            for(UploadSupplierProductExcelVo sku : list) {
                BigDecimal erpSkuPrice = priceUtil.eur2Rmb(sku.getCost()).getPrice();
                BigDecimal retailSkuPrice = sku.getOtPrice();
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(excelVo.getKeyword() + "-" + tempId+ "-" + color + "-" + sku.getSkuSize());
                storeProductAttrValue.setStock(sku.getAttrStock());
                storeProductAttrValue.setPrice(erpSkuPrice);
                if(isImgMatch) {
                	storeProductAttrValue.setImage(null != skuImg.get(sku.getSkuSize()) ? skuImg.get(sku.getSkuSize()) : mainImage);
                } else {
                	storeProductAttrValue.setImage(StringUtils.isNotBlank(sku.getSkuImage()) ? sku.getSkuImage() : sku.getImage());
                }
                storeProductAttrValue.setCost(erpSkuPrice);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailSkuPrice);
                storeProductAttrValue.setTempId(tempId);
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                List<String> suk = new ArrayList<>();
                String size = sku.getSkuSize();
                if(StringUtils.isNotBlank(sku.getSkuColor())){
                    size = sku.getSkuColor()+"-"+sku.getSkuSize();
                }
                if(StringUtils.isNotBlank(size)){
                    linkedMap.put("尺寸", size);
                    if(!sizeValueList.contains(size)){
                        sizeValueList.add(size);
                    }
                    suk.add(size);
                }
                //suk
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            //attr对象
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id
            productRequest.setMerId(supplierInfo.getMerchantId());
            productRequest.setContent(excelVo.getStoreInfo());
            productRequest.setKeyword(excelVo.getKeyword());
            productRequest.setStoreInfo(excelVo.getStoreInfo());
            productRequest.setStoreName(excelVo.getStoreName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(cost);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(cost);
            productRequest.setSourceCost(cost);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(tempId);
            //  供应商
            productRequest.setSuppliersId(supplierInfo.getSupplierId());
            productRequest.setSuppliersName(supplierInfo.getSupplierName());

            productRequest.setBarCode(barCode);
            productRequest.setCateId(excelVo.getCateId());
            productRequest.setCateIds(Collections.singletonList(excelVo.getCateId()));
            productRequest.setImage(mainImage);
            productRequest.setSliderImage(gallery.toJSONString());
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            //tod 1
            productRequest.setIsEurope(supplierInfo.getIsEurope());
            productRequest.setUnitName("件");
            productRequest.setComposition(excelVo.getComposition());
            productRequest.setDimension(excelVo.getDimension());
            productRequest.setColorCode(excelVo.getColorCode());
            productRequest.setSeasonCode(excelVo.getSeasonCode());
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setWeight(excelVo.getWeight());
            if(excelVo.getWeight() == null){
                CategoryMatch supCategoryMatch = categoryMatchService.getById(excelVo.getCateId());
                productRequest.setWeight(supCategoryMatch.getWeight());
            }
            productRequest.setProductionPlace(excelVo.getProductionPlace());
            productRequest.setCountryId(systemCountryService.getIdByName(excelVo.getCountry()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }

    private LambdaQueryWrapper<StoreProduct> getQueryWrapper(SupplierStoreProductSearchRequest request, Integer supplierId) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreProduct::getIsDel,0).eq(StoreProduct::getSuppliersId,supplierId);
        lambdaQueryWrapper.and(e->e.ne(StoreProduct::getIsEurope,ProductTypeEnum.INSIDE.getCode())
                .or(i->i.eq(StoreProduct::getIsEurope,ProductTypeEnum.INSIDE.getCode()).isNotNull(StoreProduct::getConvertIsEurope)));
        if(CollectionUtils.isNotEmpty(request.getBrandIds())){
            lambdaQueryWrapper.in(StoreProduct::getBrandId,request.getBrandIds());
        }
        if(CollectionUtils.isNotEmpty(request.getProductIds())){
            lambdaQueryWrapper.in(StoreProduct::getId,request.getProductIds());
        }
        if (CollectionUtils.isNotEmpty(request.getCateIds())) {
            List<Integer> cateIds = new ArrayList<>();
            request.getCateIds().forEach(cateId -> cateIds.addAll(categoryMatchService.getThreeChildVoListByPid(cateId).stream().map(CategoryMatch::getId).collect(Collectors.toList())));
            if(CollectionUtils.isNotEmpty(cateIds)){
                lambdaQueryWrapper.in(StoreProduct::getCateId,cateIds);
            }
        }
        if(request.getIsShow() != null){
            lambdaQueryWrapper.eq(StoreProduct::getIsShow,request.getIsShow());
        }
        lambdaQueryWrapper.eq(request.getTempId() != null, StoreProduct::getTempId, request.getTempId());
        if (StringUtils.isNotBlank(request.getKeyword())) {
            lambdaQueryWrapper.and(i -> i.or().eq(NumberUtil.isInteger(request.getKeyword()),StoreProduct::getId, request.getKeyword())
                    .or().like(StoreProduct::getStoreName, request.getKeyword())
                    .or().like(StoreProduct::getKeyword, request.getKeyword())
                    .or().like(StoreProduct::getBarCode, request.getKeyword()));
        }
        if (StringUtils.isNotBlank(request.getSeasonCode())) {
            if ("-1".equals(request.getSeasonCode())) {
                lambdaQueryWrapper.isNull(StoreProduct::getSeasonCode);
            } else {
                lambdaQueryWrapper.likeRight(StoreProduct::getSeasonCode, request.getSeasonCode());
            }
        }
        if(request.getCommodityType() != null){
            lambdaQueryWrapper.eq(StoreProduct::getCommodityType,request.getCommodityType());
        }
        //类型搜索
        switch (request.getType()) {
            case 1:
                lambdaQueryWrapper.eq(StoreProduct::getIsShow,true);
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                break;
            case 2:
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                break;
            case 3:
                //已售罄
                lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 4:
                //警戒库存
                //Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                lambdaQueryWrapper.le(StoreProduct::getStock, 2);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 5:
                //回收站
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                break;
            default:
                break;
        }
        lambdaQueryWrapper.orderByDesc(StoreProduct::getLastPushTime);
        return lambdaQueryWrapper;
    }

    @Override
    public StoreProductUpload importProductList2(List<UploadSupplierProductExcel2Vo> list, Integer merId) {
        //获取供应商信息
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        //导入商品总数
        int total = list.size();
        int totlStock = 0;
        int sum = 0;
        Iterator<UploadSupplierProductExcel2Vo> it = list.iterator();
        //循环上传商品列表
        while(it.hasNext()){
            UploadSupplierProductExcel2Vo excelVo = it.next();

            String keyword = excelVo.getKeyword();
            BigDecimal cost = excelVo.getCost();
            BigDecimal ot_price = excelVo.getOtPrice();
            String suk = excelVo.getSkuSize();
            Integer stock = excelVo.getAttrStock();
            PriceResult priceResult = new PriceResult();

            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            if (!StringUtils.isBlank(keyword)) {

                StoreProductNorm storeProductNorm = storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
                        .eq(StoreProductNorm::getKeyword, keyword)
                        .last("LIMIT 1"));

                if(null != storeProductNorm){

                      StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery()
                            .eq(StoreProduct::getKeyword, keyword)
                            .eq(StoreProduct::getBarCode, storeProductNorm.getBarCode())
                            .eq(StoreProduct::getIsDel, false)
                            .last("LIMIT 1"));

                    if(null != storeProduct)
                    {

                        StoreProduct storeProductData = new StoreProduct();

                        priceResult =  priceUtil.eur2Rmb(cost);

//                    BeanUtils.copyProperties(storeProduct, storeProductData);

                        String barcode = supplierInfo.getBarcode()+keyword+"-"+storeProduct.getTempId();
                        if(StringUtils.isNotBlank(storeProductNorm.getColorCode())){
                            barcode = barcode + "-" + storeProductNorm.getColorCode();
                        }

                        StoreProduct storeProductOld = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery()
                                .eq(StoreProduct::getKeyword, keyword)
                                .eq(StoreProduct::getIsDel, false)
                                .eq(StoreProduct::getSuppliersId, supplierInfo.getSupplierId())
                                .eq(StoreProduct::getBarCode, barcode)
                                .last("LIMIT 1"));

                        if(null != storeProductOld){
//                        storeProductData.setId(null);
                            BeanUtils.copyProperties(storeProductOld, storeProductData);
                        }else
                        {
                            BeanUtils.copyProperties(storeProduct, storeProductData);
                            storeProductData.setId(null);
                        }

                        storeProductData.setBarCode(barcode);

                        storeProductData.setMerId(supplierInfo.getMerchantId());
                        storeProductData.setIsEurope(supplierInfo.getIsEurope());
                        storeProductData.setSuppliersId(supplierInfo.getSupplierId());
                        storeProductData.setSuppliersName(supplierInfo.getSupplierName());

                        storeProductData.setCreateTime(new Date());
                        storeProductData.setUpdateTime(new Date());

                        storeProductData.setPrice(priceResult.getPrice());
                        storeProductData.setCost(priceResult.getPrice());
                        storeProductData.setSourceCost(priceResult.getPrice());
                        storeProductData.setOtPrice(ot_price);

                        boolean save  = storeProductService.saveOrUpdate(storeProductData);

                        if (!save) {
                            log.info("--------------- 新增商品失败, 商品id: {} ---------------", storeProductData.getId());
                            throw new CrmebException("新增商品失败");
                        }

                        //eb_store_product_attr_value
                        StoreProductAttrValue singleAttrValueOld = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery()
                                .eq(StoreProductAttrValue::getProductId, storeProduct.getId())
                                .eq(StoreProductAttrValue::getSuk, suk)
                                .last("LIMIT 1"));

                        if(null!=singleAttrValueOld){  //有数据

                            StoreProductAttrValue  storeProductAttrValueNew = new StoreProductAttrValue();

                            StoreProductAttrValue storeProductAttrValueOld = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery()
                                    .eq(StoreProductAttrValue::getProductId, storeProductData.getId())
                                    .eq(StoreProductAttrValue::getSuk, suk)
                                    .last("LIMIT 1"));

                            if(null!=storeProductAttrValueOld){ //有数据

                                LambdaUpdateWrapper<StoreProductAttrValue> luw = new LambdaUpdateWrapper<>();
                                luw.set(StoreProductAttrValue::getStock, stock);
                                luw.set(StoreProductAttrValue::getSuk, suk);
                                luw.set(StoreProductAttrValue::getPrice, priceResult.getPrice());
                                luw.set(StoreProductAttrValue::getCost, priceResult.getPrice());
                                luw.set(StoreProductAttrValue::getOtPrice, ot_price);

                                luw.eq(StoreProductAttrValue::getProductId, storeProductData.getId());
                                luw.eq(StoreProductAttrValue::getSuk, suk);

                                storeProductAttrValueService.update(luw);

                            }else
                            {
                                BeanUtils.copyProperties(singleAttrValueOld, storeProductAttrValueNew);

                                storeProductAttrValueNew.setProductId(storeProductData.getId())
                                        .setStock(stock)
                                        .setSuk(suk)
                                        .setAttrValue("{\"尺寸\":\"" + suk + "\"}")
                                        .setSales(0)
                                        .setPrice(priceResult.getPrice())
                                        .setCost(priceResult.getPrice())
                                        .setSourceCost(priceResult.getPrice())
                                        .setBarCode(storeProductData.getBarCode())
                                        .setSourceSkuId(storeProductData.getBarCode()+"-默认")
                                        .setImage(singleAttrValueOld.getImage())
                                        .setOtPrice(ot_price);

                                boolean saveOrUpdateResult = storeProductAttrValueService.save(storeProductAttrValueNew);
                            }
                        }else    //没有数据
                        {

                            StoreProductAttrValue  storeProductAttrValueNew = new StoreProductAttrValue();

                            StoreProductAttrValue storeProductAttrValueOld = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery()
                                    .eq(StoreProductAttrValue::getProductId, storeProductData.getId())
                                    .eq(StoreProductAttrValue::getSuk, suk)
                                    .last("LIMIT 1"));

                            if(null!=storeProductAttrValueOld){ //有数据

                                LambdaUpdateWrapper<StoreProductAttrValue> luw = new LambdaUpdateWrapper<>();
                                luw.set(StoreProductAttrValue::getStock, stock);
                                luw.set(StoreProductAttrValue::getSuk, suk);
                                luw.set(StoreProductAttrValue::getPrice, priceResult.getPrice());
                                luw.set(StoreProductAttrValue::getCost, priceResult.getPrice());
                                luw.set(StoreProductAttrValue::getOtPrice, ot_price);
                                luw.set(StoreProductAttrValue::getImage, storeProductNorm.getImage());

                                luw.eq(StoreProductAttrValue::getProductId, storeProductData.getId());
                                luw.eq(StoreProductAttrValue::getSuk, suk);

                                storeProductAttrValueService.update(luw);

                            }else
                            {
//                            BeanUtils.copyProperties(singleAttrValueOld, storeProductAttrValueNew);

                                storeProductAttrValueNew.setProductId(storeProductData.getId())
                                        .setStock(stock)
                                        .setSuk(suk)
                                        .setAttrValue("{\"尺寸\":\"" + suk + "\"}")
                                        .setSales(0)
                                        .setPrice(priceResult.getPrice())
                                        .setCost(priceResult.getPrice())
                                        .setSourceCost(priceResult.getPrice())
                                        .setBarCode(storeProductData.getBarCode())
                                        .setSourceSkuId(storeProductData.getBarCode()+"-默认")
                                        .setOtPrice(ot_price)
                                        .setImage(storeProductNorm.getImage());

                                boolean saveOrUpdateResult = storeProductAttrValueService.save(storeProductAttrValueNew);
                            }

                        }


                        //eb_store_product_attr数据
                        StoreProductAttr storeProductAttrsNew = storeProductAttrService.getStoreProductAttrDetail(storeProductData.getId(),"尺寸");

                        if(null!=storeProductAttrsNew){    //有数据 更新

                            List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueService.getListByProductId(storeProductData.getId());

                            String attrValue = "";
                            for(StoreProductAttrValue storeProductAttrValue : storeProductAttrValueList){

                                attrValue = storeProductAttrValue.getSuk() + "," + attrValue ;

                            }

                            String sttrName = "尺寸";

                            LambdaUpdateWrapper<StoreProductAttr> luw = new LambdaUpdateWrapper<>();
                            luw.set(StoreProductAttr::getAttrValues, attrValue);

                            luw.eq(StoreProductAttr::getProductId, storeProductData.getId());
                            luw.eq(StoreProductAttr::getAttrName, sttrName);

                            boolean  saveRet = storeProductAttrService.update(luw);

//                        storeProductAttrsNew.setAttrValues(attrValue);

//                        boolean  saveRet  = storeProductAttrService.update(storeProductAttrsNew);

                            if (!saveRet) {
                                log.info("--------------- 新增多属性名失败, 商品id: {} ---------------", storeProduct.getId());
                                throw new CrmebException("新增属性名失败");
                            }

                        }else  //无数据 新增
                        {

                            List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueService.getListByProductId(storeProductData.getId());

                            StringBuilder attrValue = new StringBuilder();
                            for(StoreProductAttrValue storeProductAttrValue : storeProductAttrValueList){
                                attrValue.append(storeProductAttrValue.getSuk());
                                attrValue.append(",");

                            }
                            attrValue =  attrValue.deleteCharAt(attrValue.length()-1);

                            StoreProductAttr storeProductAttrsNew2 = new StoreProductAttr();
                            storeProductAttrsNew2.setProductId(storeProductData.getId());
                            storeProductAttrsNew2.setAttrName("尺寸");
                            storeProductAttrsNew2.setAttrValues(attrValue.toString());
                            storeProductAttrsNew2.setBarCode(barcode);

                            boolean  saveRet  = storeProductAttrService.save(storeProductAttrsNew2);

                            if (!saveRet) {
                                log.info("--------------- 新增多属性名失败, 商品id: {} ---------------", storeProduct.getId());
                                throw new CrmebException("新增属性名失败");
                            }

                        }

                        //eb_store_product_attr_result 数据
                        StoreProductAttrResult storeProductAttrResultOld = storeProductAttrResultService.getByProductId(storeProductData.getId());

                        if(null!=storeProductAttrResultOld){    //有数据 更新

                            List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueService.getListByProductId(storeProductData.getId());
                            JSONArray newJa = new JSONArray();
                            String attrValue = "";
                            for(StoreProductAttrValue storeProductAttrValue : storeProductAttrValueList){

                                JSONObject jo = new JSONObject();
                                jo.put("cost", storeProductAttrValue.getCost());
                                jo.put("price", storeProductAttrValue.getPrice());
                                jo.put("sourceCost", storeProductAttrValue.getSourceCost());
                                jo.put("stock", storeProductAttrValue.getStock());
                                jo.put("attrValue", storeProductAttrValue.getAttrValue());
                                jo.put("barCode", storeProductAttrValue.getBarCode());
                                jo.put("otPrice", storeProductAttrValue.getOtPrice());
                                jo.put("productId", storeProductAttrValue.getOtPrice());
                                jo.put("image", storeProductAttrValue.getImage());
                                jo.put("sourceSkuId", storeProductAttrValue.getSourceSkuId());
                                jo.put("suk", storeProductAttrValue.getSuk());
                                newJa.add(jo);
                                totlStock = totlStock + storeProductAttrValue.getStock();
                            }

                            storeProductAttrResultOld.setResult(newJa.toJSONString());

                            LambdaUpdateWrapper<StoreProductAttrResult> luw = new LambdaUpdateWrapper<>();
                            luw.set(StoreProductAttrResult::getResult, newJa.toJSONString());
                            luw.eq(StoreProductAttrResult::getProductId, storeProductData.getId());

                            boolean  saveRet = storeProductAttrResultService.update(luw);

//                        boolean  saveRet  = storeProductAttrResultService.update(storeProductAttrResultOld);

                            if (!saveRet) {
                                log.info("--------------- 新增多属性名失败, 商品id: {} ---------------", storeProduct.getId());
                                throw new CrmebException("新增属性名失败");
                            }

                        }else  //无数据 新增
                        {

                            StoreProductAttrResult   storeProductAttrResultNew = new StoreProductAttrResult();
                            List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueService.getListByProductId(storeProductData.getId());
                            JSONArray newJa = new JSONArray();
                            String attrValue = "";
                            for(StoreProductAttrValue storeProductAttrValue : storeProductAttrValueList){

                                JSONObject jo = new JSONObject();
                                jo.put("cost", storeProductAttrValue.getCost());
                                jo.put("price", storeProductAttrValue.getPrice());
                                jo.put("sourceCost", storeProductAttrValue.getSourceCost());
                                jo.put("stock", storeProductAttrValue.getStock());
                                jo.put("attrValue", storeProductAttrValue.getAttrValue());
                                jo.put("barCode", storeProductAttrValue.getBarCode());
                                jo.put("otPrice", storeProductAttrValue.getOtPrice());
                                jo.put("productId", storeProductAttrValue.getOtPrice());
                                jo.put("image", storeProductAttrValue.getImage());
                                jo.put("sourceSkuId", storeProductAttrValue.getSourceSkuId());
                                jo.put("suk", storeProductAttrValue.getSuk());
                                newJa.add(jo);

                                totlStock = totlStock + storeProductAttrValue.getStock();
                            }

                            storeProductAttrResultNew.setProductId(storeProductData.getId());
                            storeProductAttrResultNew.setChangeTime(DateUtil.getSecondTimestamp());
                            storeProductAttrResultNew.setBarCode(barcode);
                            storeProductAttrResultNew.setResult(newJa.toJSONString());

                            boolean  saveRet  = storeProductAttrResultService.save(storeProductAttrResultNew);

                            if (!saveRet) {
                                log.info("--------------- 新增多属性名失败, 商品id: {} ---------------", storeProduct.getId());
                                throw new CrmebException("新增属性名失败");
                            }

                        }


                        //更新图片

                        StoreProductDescription storeProductDescriptionOld = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
                                .eq(StoreProductDescription :: getProductId,  storeProduct.getId())
                                .last("LIMIT 1")
                        );

                        if(null!=storeProductDescriptionOld){  //有数据
                            StoreProductDescription storeProductDescriptionNew = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
                                    .eq(StoreProductDescription :: getProductId,  storeProductData.getId())
                                    .last("LIMIT 1")
                            );

                            if(null!=storeProductDescriptionNew){  //有数据

//                                LambdaUpdateWrapper<StoreProductDescription> luw = new LambdaUpdateWrapper<>();
//
//                                luw.set(StoreProductDescription::getImage, storeProductDescriptionOld.getImage());
//                                luw.set(StoreProductDescription::getSliderImage, storeProductDescriptionOld.getSliderImage());
//                                luw.set(StoreProductDescription::getUnitName, storeProductDescriptionOld.getUnitName());
//
//                                luw.set(StoreProductDescription::getComposition, storeProductDescriptionOld.getComposition());
//                                luw.set(StoreProductDescription::getUnitName, storeProductDescriptionOld.getUnitName);
//
//                                luw.set(StoreProductDescription::getAttrValues, attrValue);
//
//                                luw.eq(StoreProductDescription::getProductId, storeProductData.getId());
//
//                                boolean  saveRet = storeProductDescriptionService.update(luw);


                            }else
                            {
                                StoreProductDescription storeProductDescriptionAddData = new StoreProductDescription();

                                BeanUtils.copyProperties(storeProductDescriptionOld,storeProductDescriptionAddData);

                                storeProductDescriptionAddData.setProductId(storeProductData.getId());
                                storeProductDescriptionAddData.setId(null);

                                storeProductDescriptionService.saveOrUpdate(storeProductDescriptionAddData);

                            }
                        }

                        //更新总库存

                        LambdaUpdateWrapper<StoreProduct> luw = new LambdaUpdateWrapper<>();
                        luw.set(StoreProduct::getStock, totlStock);
                        luw.eq(StoreProduct::getId, storeProductData.getId());

                        storeProductService.update(luw);
                        totlStock = 0;

                    }else
                    {

                        log.info("--------------- 商品库不存在, 商品keyword: {} ---------------", keyword);
//                    throw new CrmebException("新增属性名失败");
                    }

                }else
                {

                    log.info("--------------- 标准商品不存在, 商品keyword: {} ---------------", keyword);
//                    throw new CrmebException("新增属性名失败");

                }

            }

            log.info("getKeyword:" + keyword);
        }

        String msg = "总计:"+total+",成功:"+list.size();
        StoreProductUpload storeProductUpload = new StoreProductUpload();
        storeProductUpload.setMsg(msg);
        storeProductUpload.setSupplierId(supplierInfo.getSupplierId());
        storeProductUploadService.save(storeProductUpload);
        return storeProductUpload;
    }
}
